import asyncio
import edge_tts
from pydub import AudioSegment
import tempfile
import os
import io

async def text_to_ogg(text: str, output_file: str, voice: str = "zh-CN-YunxiNeural"):
    communicate = edge_tts.Communicate(text, voice)
    mp3_data = bytearray()
    
    # Collect all chunks and ensure completion
    async for chunk in communicate.stream():
        if chunk["type"] == "audio":
            mp3_data.extend(chunk["data"])
    
    # Add a small delay to ensure buffer completion
    await asyncio.sleep(0.1)
    
    # Verify we have data before processing
    if len(mp3_data) > 0:
        audio = AudioSegment.from_file(io.BytesIO(mp3_data), format="mp3")
        audio = audio.set_frame_rate(22050).set_channels(1)
        audio.export(output_file, format="ogg", codec="libopus", bitrate="13k")
    else:
        raise Exception("No audio data received")

def convert_text_to_ogg(text: str, output_file: str, voice: str = "zh-CN-YunxiNeural"):
    """Synchronous wrapper for text_to_ogg"""
    asyncio.run(text_to_ogg(text, output_file, voice))

# Usage
text = "你好，欢迎使用文本转语音功能！"
string_list = [
    "哥们， 我要大力击球啦",
    "伙计， 来个中力击球么",
    "亲， 小力击球，走起"
]

convert_text_to_ogg(text, "output.ogg")    
convert_text_to_ogg(string_list[0], "dali.ogg")
convert_text_to_ogg(string_list[1], "zhgli.ogg")
convert_text_to_ogg(string_list[2], "xiaoli.ogg")
